package com.oceansoft.mobile.oauth.controller;

import com.alibaba.fastjson.JSONObject;
import com.oceansoft.mobile.common.util.HttpClientUtil;
import com.oceansoft.mobile.common.util.Result;
import com.oceansoft.mobile.oauth.service.SecurityServiceImpl;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import java.io.IOException;

import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.POST;
/**
 * Created by BEN on 2016/5/1.
 */

@Controller
@RequestMapping("security")
public class OAuthController {

    @Resource
    private SecurityServiceImpl security;

    @RequestMapping(value = "validate", method = GET)
    @ResponseBody
    public Result validate(HttpSession session, @RequestParam("app_id") String app_id, @RequestParam("access_token") String access_token) {
        if (security.validateToken(access_token)) {
            session.setAttribute("access_token", access_token);
            session.setAttribute("app_id", app_id);
            return new Result(access_token);
        }
        return new Result();
    }

    @RequestMapping(value = "token", method = POST)
    @ResponseBody
    public Result token(@RequestParam("client_id") String client_id, @RequestParam("client_secret") String client_secret) throws IOException {
        Result result = new Result();
//        String url = "http://172.16.3.7:8085/connect/oauth/token?grant_type=client_credentials";
        String url = "http://wjw.szgaj.cn/connect/oauth/token?grant_type=client_credentials";
        url+="&client_id="+client_id+"&client_secret="+client_secret;
        System.out.println("认证地址::::::::::::"+url);
        try { 
           String str = HttpClientUtil.doPost(url,null,null);
            if(str!=null){
                result.setData(JSONObject.parseObject(str));
                result.setMsg("获取token成功");
                result.setStatusCode(200);
                result.setSucc(true);
                result.setTime(System.currentTimeMillis());
            }else{
                result.setData(null);
                result.setMsg("获取token失败");
                result.setStatusCode(200);
                result.setSucc(false);
                result.setTime(System.currentTimeMillis());
            }

        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }
}
